<script setup>
import { showToast } from 'vant';
import {sendSignUpCaptcha} from "@/api/business.js";


const modelValue = defineModel()

const props = defineProps({

  name: {
    type: String,
    default: ''
  },
  label: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: ''
  },
  phone: {
    type: String,
    default: ''
  },


})

const attrs = useAttrs()

const state = reactive({
  text: '发送验证码',
  time: 60,
  timer: undefined,
  disable: false,
})

onMounted(()=>{
  const time = localStorage.getItem('time')
  if (time && time > 0) {
    state.text = time + 's后重新发送'
    state.time = time
    handleSend()
  };
})

const emits = defineEmits(['getCode'])
const _handleSend = (e) =>{
  e.preventDefault()
  // sendCaptcha(this.registerFormStepFirst.phonenumber).then(res => {
  //   if(res.code == 200){
  //     let uuid = res.data.uuid
  //     this.registerFormStepFirst.uuid = uuid
  //     this.handleSend()
  //   }
  // })

  if(!props.phone){
    return showToast("请输入手机号码")
  }
  if(!/^1[3-9]\d{9}$/.test(props.phone)){
    return showToast("手机号码格式错误")
  }


  sendSignUpCaptcha(props.phone).then(res =>{
    if(res.code == 200){
      let uuid = res.data.uuid
      emits('getCode', uuid)

      showToast("发送成功")
      handleSend()
    }else{
      showToast("发送失败")
    }
  })
}

const handleSend = () =>{

  state.disable = true
  state.text = state.time + 's后重新发送'
  state.timer = setInterval(() => {
    if (state.time > 0) {
      state.time--
      state.text = state.time + 's后重新发送'
      localStorage.setItem('time', state.time) // 注意这行
    } else {
      clearInterval(state.timer)
      state.time = 60
      state.disable = false
      state.text = '重新发送'
    }
  }, 1000)



}





</script>

<template>
  <van-field
    v-bind="attrs"
    v-model="modelValue"
    type="text"
    :name="name"
    :label="label"
    :placeholder="placeholder"
  >
    <template #button>
      <button  @click.stop="_handleSend" :disabled="state.disable" class="van-button--primary  van-button--round van-button--plain van-button--hairline">{{state.text}}</button>
    </template>
<!--    <template #button>-->
<!--      <van-button :disabled="state.disable" plain text size="mini" >{{state.text}}</van-button>-->
<!--    </template>-->
  </van-field>


</template>

<style scoped>

</style>
